import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/navigation/navigation_logic.dart';
import 'package:ball_lion/service/config_service.dart';
import 'package:ball_lion/service/connect_service.dart';
import 'package:ball_lion/service/match_service.dart';
import 'package:ball_lion/service/push_service.dart';
import 'package:ball_lion/service/resource_service.dart';
import 'package:ball_lion/service/scheme_service.dart';
import 'package:ball_lion/service/third_login_service.dart';
import 'package:ball_lion/service/umeng_service.dart';
import 'package:ball_lion/entity/other/error_info_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/resources/theme.dart';
import 'package:ball_lion/server/http/request_header.dart';
import 'package:ball_lion/utils/app_config.dart';
import 'package:ball_lion/utils/attach_detector.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/overlay/ads_float_widget.dart';
import 'package:ball_lion/module/launch_page.dart';
import 'package:ball_lion/module/overlay/app_float_widget.dart';
import 'package:ball_lion/widgets/resource_dialog.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';

void main() async {
  UmengApmSdk(
    name: 'qiukedao',
    bver: '2.9.2',
    flutterVersion: '3.13.4',
    engineVersion: '9064459a8b',
    enableLog: true,
    errorFilter: {
      "mode": "ignore",
      "rules": [],
    },
    initFlutterBinding: ApmWidgetsFlutterBinding.ensureInitialized,
    onError: (exception, stack) {
      log('exception: $exception  stack: $stack');
      if (exception is ArgumentError &&
          exception.message == 'No host specified in URI ') return;
      if (Get.previousRoute != "/" && AppConfig.config.channel == "c88888") {
        if (SpUtils.showErrorToast) Toast.text(exception.toString());
        SpUtils.setErrorInfo(ErrorInfoEntity(
            time: DateTime.now().formatedString(),
            stack: stack.toString(),
            exception: exception.toString(),
            path: Get.currentRoute == Routes.navigation &&
                    Get.previousRoute != "/"
                ? Get.find<NavigationLogic>().currentRoute
                : Get.currentRoute));
      }
    },
  ).init(appRunner: (observer) async {
    await AppConfig.init();
    await SpUtils.initSp();
    await RequestHeader.preInit();

    await AppConfig.config.getLimit();
    await initService();
    await Get.find<ResourceService>().getAppLaunchConfig();
    //await Fluwx().registerApi(appId: Constant.wxAppId);

    return MyApp(navigatorObserver: observer);
  });
}

Future initService() async {
  Get.putAsync(() => ConnectService().init());
  Get.putAsync(() => MatchService().init());
  Get.putAsync(() => ResourceService().init());
  // Get.putAsync(() => UmengService().init());
  Get.putAsync(() => PushService().init());
  Get.putAsync(() => ThirdLoginService().init());
  Get.putAsync(() => ConfigService().init());
  Get.putAsync(() => SchemeService().init());
  // Get.putAsync(() => BaiduService().init());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key, this.navigatorObserver});

  final NavigatorObserver? navigatorObserver;
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  late WeChatResponseSubscriber weChatListener;

  @override
  void initState() {
    super.initState();
    EasyLoading.instance.userInteractions = false;

    EasyRefresh.defaultHeaderBuilder = () {
      return Styles.refreshHeader();
    };

    EasyRefresh.defaultFooterBuilder = () {
      return Styles.refreshFooter();
    };

    Connectivity().onConnectivityChanged.listen((event) {
      log("connectivity $event");
      RequestHeader.setNetworkInfo(event);
    });

    if (!kIsWeb) {
      SystemUiOverlayStyle style = const SystemUiOverlayStyle(
          statusBarColor: Colours.transparent,
          statusBarBrightness: Brightness.dark,
          statusBarIconBrightness: Brightness.dark);
      SystemChrome.setSystemUIOverlayStyle(style);
    }
    AppLifecycleListener(onResume: () async {
      User.fetchUserInfo();
      Get.find<ConnectService>().startListen();
      AttachDetector.cancelWarn();
    }, onInactive: () {
      Get.find<ConfigService>().saveConfigToLocal();
    }, onPause: () {
      Get.find<ConnectService>().stopListen();
      Utils.onEvent('app_exit');
      AttachDetector.warn();
    }, onHide: () {
      Get.find<ConnectService>().stopListen();
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
        title: '球狮体育',
        color: Colours.white,
        theme: AppTheme.mainTheme(),
        debugShowCheckedModeBanner: false,
        getPages: Routes.getPages,
        home: const QsLaunchPage(),
        locale: Get.deviceLocale,
        defaultTransition: Transition.rightToLeft,
        transitionDuration: const Duration(milliseconds: 100),
        localizationsDelegates: const [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        fallbackLocale: const Locale("zh", "CN"),
        supportedLocales: const [
          Locale.fromSubtags(languageCode: 'zh', countryCode: 'CN'),
          Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
        ],
        navigatorObservers: <NavigatorObserver>[
          // widget.navigatorObserver ?? ApmNavigatorObserver.singleInstance,
          HeroController()
        ],
        routingCallback: (value) {
          if (SpUtils.agreePrivacy != true) {
            return;
          }
          ResourceDialogUtil.checkShowDialog();
          if (value?.current == Routes.navigation && value?.previous != '/') {
            var route = Get.find<NavigationLogic>().currentRoute;
            AdsFloatWidget.checkAds(route);
          } else {
            AdsFloatWidget.checkAds(value?.current);
          }
        },
        builder: EasyLoading.init(
          builder: (context, child) {
            return AppFloatWidget(child: child);
          },
        ));
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      User.fetchUserInfo();
    } else if (state == AppLifecycleState.inactive) {
      log('------inactive');
      Get.find<ConfigService>().saveConfigToLocal();
    } else if (state == AppLifecycleState.detached) {
      log('------detached');
    } else if (state == AppLifecycleState.paused) {
      log('------paused');
    }
    super.didChangeAppLifecycleState(state);
  }
}
